#include <cserver/restapi.h>
#include <boost/log/trivial.hpp>
#include <boost/format.hpp>
#include <pqxx/transaction.hxx>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/common/logout";

	std::string makeLogoutResponse(const std::string& account, bool success, const std::string& message, const std::string& name){
		std::stringstream sstr;
		sstr << boost::format(R"({
"func":"logout",
"args":{},
"ret":{"success":%1%, "message":%2%,
"value":{"account":%3%, 
"name": %4% }}
})") 
			% std::string(success ? "true" : "false") % escape_string(message) % escape_string(account) % escape_string(name);

			return sstr.str();

	}
	void logout(Request& req, pqxx::connection& dbconn, SessionContext& sctx, const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto sessionid = req.getCookie("sessionid");
		bool success = false;
		std::string account, displayName, message;
		{
			std::lock_guard<std::mutex> lock(sctx.mutex);
			auto pos = sctx.activeSessions.find(sessionid);
			if (pos != sctx.activeSessions.end())
			{
				auto itr = sctx.user_info.find(pos->second);
				account = pos->second;
				displayName = itr->second.displayName;

				sctx.activeSessions.erase(sessionid);
				pqxx::work w(dbconn);
				w.prepared("delete_sessionid")(sessionid).exec();
				w.commit();
				success = true;
			}
			else
				message = "sessionid not found";
		}
		StreamGroup sg(req);
		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";
		sg.fout <<  makeLogoutResponse(account, success, message, displayName);
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("POST", webcmd::K_this_command, &webcmd::logout);
}

